package com.ruoyi.socket.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.util.Locale;

@Slf4j
public class WebsocketUtils {

    private final static String mHexStr = "0123456789ABCDEF";

    public static String[] getClientPort(ChannelHandlerContext ctx) {
        return ctx.channel().remoteAddress().toString()
                .replace("[", "")
                .replace("]", "")
                .replace("/", "")
                .split(":");
    }

    public static String[] getServerPort(ChannelHandlerContext ctx) {
        return ctx.channel().localAddress().toString()
                .replace("[", "")
                .replace("]", "")
                .replace("/", "")
                .split(":");
    }

    /**
     * 十六进制字符串转换成 ASCII字符串
     *
     * @param str String Byte字符串
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr) {
        hexStr = hexStr.toString().trim().replace(" ", "").toUpperCase(Locale.US);
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int iTmp = 0x00;
        ;

        for (int i = 0; i < bytes.length; i++) {
            iTmp = mHexStr.indexOf(hexs[2 * i]) << 4;
            iTmp |= mHexStr.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (iTmp & 0xFF);
        }
        return new String(bytes);
    }

    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            bf.put(b);
        }
        return bf.array();
    }

    public static String getMsg(ByteBuf buf) {
        //junior
        byte[] bytes = new byte[buf.readableBytes()];
        for (int i = 0; i < buf.readableBytes(); i++) {
            bytes[i] = buf.getByte(i);
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * @param n
     * @Title: intTohex
     * @Description: int型转换成16进制
     * @return: String
     */
    public static String intTohex(int n) {
        StringBuffer s = new StringBuffer();
        String a;
        char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        if ("".equals(a)) {
            a = "00";
        }
        if (a.length() == 1) {
            a = "0" + a;
        }
        return a;
    }

    /**
     * 将16进制字符串数转换为汉字,可包含数字及符号<br>
     * 方 法 名：HexToUnicode <br>
     * 创 建 人： <br>
     * 创建时间：2015-12-11 下午2:58:48 <br>
     * 修 改 人： <br>
     * 修改日期： <br>
     * @param content
     * @return String
     */
    public static String HexToUnicode(String content) {
        String enUnicode = null;
        String deUnicode = null;
        for (int i = 0; i < content.length(); i++) {
            if (enUnicode == null) {
                enUnicode = String.valueOf(content.charAt(i));
            } else {
                enUnicode = enUnicode + content.charAt(i);
            }
            if (i % 4 == 3) {
                if (enUnicode != null) {
                    if (deUnicode == null) {
                        deUnicode = String.valueOf((char) Integer.valueOf(enUnicode, 16).intValue());
                    } else {
                        deUnicode = deUnicode + String.valueOf((char) Integer.valueOf(enUnicode, 16).intValue());
                    }
                }
                enUnicode = null;
            }

        }
        return deUnicode;
    }

    /**
     * 将汉字转换为16进制字符串数,可包含数字及符号<br>
     * 方 法 名：UnicodeToHex <br>
     * 创 建 人： <br>
     * 创建时间：2015-12-11 下午2:59:31 <br>
     * 修 改 人： <br>
     * 修改日期： <br>
     * @param content
     * @return String
     */
    public static String UnicodeToHex(String content) {
        String enUnicode = null;
        for (int i = 0; i < content.length(); i++) {
            if (i == 0) {
                enUnicode = getHexString(Integer.toHexString(content.charAt(i)).toUpperCase());
            } else {
                enUnicode = enUnicode + getHexString(Integer.toHexString(content.charAt(i)).toUpperCase());
            }
        }
        return enUnicode;
    }

    private static String getHexString(String hexString) {
        String hexStr = "";
        for (int i = hexString.length(); i < 4; i++) {
            if (i == hexString.length())
                hexStr = "0";
            else
                hexStr = hexStr + "0";
        }
        return hexStr + hexString;
    }

    public static void main(String[] args) {
        String str = "王江波1234是一个小朋友，HOHOHOHO";
        System.out.println(WebsocketUtils.UnicodeToHex("王江波"));
        // 打印出
        // 738B6C5F6CE2662F4E004E2A5C0F670B53CBFF0C0048004F0048004F0048004F0048004F
        str = "738B6C5F6CE2";
        System.out.println(WebsocketUtils.HexToUnicode(str));
        // 打印出 王江波是一个小朋友，HOHOHOHO

    }
}
